import React, {useState, useRef, useEffect, useContext} from 'react';
import { Markmap } from 'markmap-view';
import { transformer } from './markmap';
import { Toolbar } from 'markmap-toolbar';
import 'markmap-toolbar/dist/style.css';
import {Message} from "@/types/chat";
import {create} from "zustand";
interface MarkMapState {
    message: string;
    createMarkMap: (msg: Message) => void;
    initValue: string;
}

function renderToolbar(mm: Markmap, wrapper: HTMLElement) {
    while (wrapper?.firstChild) wrapper.firstChild.remove();
    if (mm && wrapper) {
        const toolbar = new Toolbar();
        toolbar.attach(mm);
        // Register custom buttons
        toolbar.register({
            id: 'alert',
            title: 'Click to show an alert',
            content: 'Alert',
            onClick: () => alert('You made it!'),
        });
        toolbar.setItems([...Toolbar.defaultItems, 'alert']);
        wrapper.append(toolbar.render());
    }
}

export default function MarkmapHooks() {
    const { initValue } = useMarkMap();
    const [value, setValue] = useState(initValue);
    // Ref for SVG element
    const refSvg = useRef<SVGSVGElement>();
    // Ref for markmap object
    const refMm = useRef<Markmap>();
    // Ref for toolbar wrapper
    const refToolbar = useRef<HTMLDivElement>();

    useEffect(() => {
        // Create markmap and save to refMm
        if (refMm.current) return;
        const mm = Markmap.create(refSvg.current);
        console.log('create', refSvg.current);
        refMm.current = mm;
        renderToolbar(refMm.current, refToolbar.current);
    }, [refSvg.current]);

    useEffect(() => {
        // Update data for markmap once value is changed
        const mm = refMm.current;
        if (!mm) return;
        const { root } = transformer.transform(value);
        mm.setData(root);
        mm.fit();
    }, [refMm.current, value]);

    const handleChange = (e) => {
        setValue(e.target.value);
    };

    return (
        <React.Fragment>
            <div className="flex-1">
        <textarea
            className="w-full h-full border border-gray-400"
            value={value}
            onChange={handleChange}
        />
            </div>
            <svg className="flex-1" ref={refSvg} />
        </React.Fragment>
    );
}

export const useMarkMap = create<MarkMapState>()((set) => ({
    message: '',
    initValue: '',
    createMarkMap: (msg: Message) => {
        if (isMarkdownFormat()) {
            set((prevState) => ({
                // 更新initValue和message状态
                initValue: `# markmap

- beautiful
- useful
- easy
- interactive
`,
                message: msg.content,
            }));
        }
    },
}));
const isMarkdownFormat = () => {
    return true;
};